/*
 * @Author: your name
 * @Date: 2022-11-04 19:07:22
 * @LastEditTime: 2023-06-12 10:49:49
 * @LastEditors: DESKTOP-4QFD9PO
 * @Description: In User Settings Edit
 * @FilePath: \ClothMes\src\api\axios.config.ts
 */
import useUserStore from '@/store/modules/user';
import { Message } from '@arco-design/web-vue';
import Axios, { AxiosResponse, AxiosError } from 'axios'
import qs from 'qs'
export let baseURL = ''
export const CONTENT_TYPE = 'Content-Type'
export const FORM_URLENCODED = 'application/x-www-form-urlencoded; charset=UTF-8'
export const APPLICATION_JSON = 'application/json; charset=UTF-8'
export const TEXT_PLAIN = 'text/plain; charset=UTF-8'
// let host = window.location.host
// let reg = /^localhost+/
// if (reg.test(host)) {
//   baseURL = '/api'
// } else {
  baseURL = '/api'
// }
const service = Axios.create({
  baseURL,
  timeout: 10 * 60 * 1000,
  withCredentials: true, // 跨域请求时发送cookie
})


service.interceptors.request.use(
  (config) => {

    !config.headers && (config.headers = {})
    if (!config.headers[CONTENT_TYPE]) {
      config.headers[CONTENT_TYPE] = APPLICATION_JSON
    }
    if (config.headers[CONTENT_TYPE] === FORM_URLENCODED) {
      config.data = qs.stringify(config.data)
    }
    config.headers['token'] = sessionStorage.getItem('USER-TOKEN-KEY') || '';
    return config
  },
  (error) => {
    return Promise.reject(error.response)
  }
)
localStorage.setItem('isSignOut', 'false')
service.interceptors.response.use(
  (response: AxiosResponse): AxiosResponse => {

    // if (response.data['code'] === 401 || response.data['code'] === 409) {
    //   Message.error('当前登录账号登录过期，系统5秒后将自动退出')
    //   localStorage.setItem('isSignOut', 'true')
    //   setTimeout(() => {
    //     useUserStore().logout().then(() => {
    //       location.reload()
    //     })
    //   }
    //     , 5000)
    //   return response
    // } else {
    //   return response
    // }

    return response
  },
  (error: AxiosError) => {

    if (import.meta["env"].MODE === 'development') {

    }
    if (error.response?.status === 401 || error.response?.status === 409) {
      const userStore = useUserStore()
      userStore.logout().then(() => {
        sessionStorage.clear()
        window.location.reload();
      })
      throw new Error('token 过期')
    } else {
      throw new Error(error.message)

    }

  }
)

export default service


/// 401 402 403

//  